let Sequelize = require('sequelize');
let db = require('../libs/db.lib');
let moment = require('moment');
let md5 = require('blueimp-md5');

let User = db.define('user', {
    // 自增ID
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true,
        unique: true,
        allowNull: false,
    },
    // 用户邮箱
    email: {
        type: Sequelize.STRING(50),
        allowNull: false,
    },
    // 密码
    password: {
        type: Sequelize.STRING(100),
        allowNull: false,
    },
    // 昵称
    nickname: {
        type: Sequelize.STRING(32),
        allowNull: false,
    },
    // token
    token: Sequelize.STRING(1024),
    // 备注
    note: Sequelize.STRING(100),
    // 禁用
    block: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: false,
    },
    // 是否验证
    verified: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: false,
    },
    // 上次验证码生成的时间
    codeGenAt: Sequelize.DATE,
    // 验证码
    verifyCode: Sequelize.STRING(6),
    // 手机号
    mobile: Sequelize.STRING(20),
    // 角色 0 管理员 1 普通用户
    role: {
        type: Sequelize.TINYINT,
        allowNull: false,
        defaultValue: 1,
    },
    // 创建时间
    createdAt: Sequelize.DATE,
    // 最后登录时间
    loginAt: Sequelize.DATE,
    // 观看历史 返回object数组
    history: {
        type: Sequelize.TEXT,
        get() {
            try {
                return JSON.parse(this.getDataValue('history'));
            } catch (e) {
                return [];
            }
        },
        set(val) {
            this.setDataValue('history', JSON.stringify(val));
        },
    },
}, {
    timestamps: false,
    // 设置索引
    indexes: [
        {
            unique: true,
            name: 'email',
            fields: ['email'],
        },
    ],
});

// 同步model到table 插入默认数据记录
User.sync({alter: true}).then(() => {
    const uName = 'admin@x.cn';
    const uPwd = 'adminxx';
    User.findOne({attributes: ['id'], where: {email: uName}}).then((u) => {
        if (!u) {
            User.create({email: uName, password: md5(uPwd), nickname: '管理大大', verified: true, role: 0, createdAt: moment().valueOf()}).then(u => {
                if (u) {
                    console.log(`默认管理员添加成功! user:${uName} pwd:${uPwd}`);
                }
            }).catch(e => {
                console.log(e);
            });
        }
    });
});

module.exports = User;
